// 处理登录,建立WS [domain;//域名  stationId;//分机号  agentId;//座席号] type 1(登录)
// 设置座席状态 stationId 分机  agentId 座席
function _setAgentState(domain, stationId, agentId,reasoncode, agentState, acdId, workMode) {
    var setReq = {
        stationId:stationId,
        agentId:agentId,
        acdId:acdId,
        domain:domain,
        agentState:agentState,
        reasonCode:reasoncode,
        workMode:workMode,
        type:"1"
    };
    domains = domain;
    stationIds=stationId;
    agentIds=agentId;
    // 发送消息
    send(setReq);
}
//坐席登陆
function _agentLogin(domain, stationId, agentId, agentPwd,reasoncode, agentState, acdId, workMode) {
    var setReq = {
        stationId:stationId,
        agentId:agentId,
        agentPwd:agentPwd,
        acdId:acdId,
        domain:domain,
        agentState:agentState,
        reasonCode:reasoncode,
        workMode:workMode,
        type:"1"
    };
    domains = domain;
    stationIds=stationId;
    agentIds=agentId;
    pwd = agentPwd;
    // 发送消息
    send(setReq);
}
// 座席登出
function _setAgentLoginOut(domain, stationId, agentId,reasoncode, agentState, acdId, workMode){
    var setReq = {
        stationId:stationId,
        agentId:agentId,
        acdId:acdId,
        domain:domain,
        agentState:agentState,
        reasonCode:reasoncode,
        workMode:workMode,
        type:"16"
    };
    send(setReq);
}

// 坐席就绪-小休玛
function _setAgentStateS(domain, stationId, agentId,reasoncode, agentState, acdId, workMode) {
    var setReq = {
        stationId:stationId,
        agentId:agentId,
        acdId:acdId,
        domain:domain,
        agentState:agentState,
        reasonCode:reasoncode,
        workMode:workMode,
        type:"17"
    };
    // 发送消息
    send(setReq);
}

// 呼叫 
function _makeCall() {
    var number = $.trim($("#callout_number").val());debugger;
    if (call1 != null || call2 != null||phone.isAfterCall == 1) {
        writeLog("_makeCall call1:"+call1.callid+"call2:"+call2.callid+
            "isAfterCall:"+phone.isAfterCall+"无法进行状态切换操作!");
        ztoDialog("message","对不起,坐席正忙,无法进行状态切换操作!");
        return;
    }
    if(number==""){
        ztoDialog("message","请输入号码！");
        return;
    }
    writeLog("make call "+ deviceId + " to " + number);
    var req = {
        agentId:phone.agtId,
        stationId:phone.deviceId,
        caller:phone.deviceId,
        callee:number,
        domain:phone.domain,
        uui:"ss123rr",
        businessScenario:phone.deviceId,
        type:"2"
    };
    // 发送消息
    send(req);
}
//保持
function _holdCall() {

    if(call1 == null){
        onMessage("没有可以保持的通话");
        return;
    }
    onMessage("_holdCall " + phone.deviceId +" - " + call1.callid );
    if(call1.state == 1){
        onMessage("振铃中没有可以保持的通话");
        return;
    }
    var req = {
        uuid: call1.callid,
        device: phone.deviceId,
        domain: phone.domain,
        type:"3"
    };
     // 发送消息
    send(req);
}
//取回
function _retrieveCall() {
    onMessage("_retrieveCall " + phone.deviceId +" - " + call1.callid );
    if(call1 == null){
        return;
    }
    var req = {
        uuid: call1.callid,
        device: phone.deviceId,
        domain: phone.domain,
        type:"4"
    };
    // 发送消息
    send(req);
}
// 应答
function _answerCall() {
    onMessage("_answerCall call " +phone.deviceId +" - " + call1.callid );
    if(call1 == null){
        ztoDialog('暂无呼叫！');
        return;
    }
    var req = {
        uuid: call1.callid,
        device: phone.deviceId,
        domain: phone.domain,
        type:"6"
    };
    // 发送消息
    send(req);
}
// 咨询
function _consultCall(devId) {
    
    onMessage("_consultCall " + phone.deviceId +" - " + call1.callid +" to "+ devId );
    var req = {
        uuid: call1.callid,
		agentId:phone.agtId,
        device: phone.deviceId,
        domain: phone.domain,
        consultDevice: devId,
        businessScenario:phone.deviceId,
        uui:"",
        type:"10"
    };
    send(req);
}

function _alternateCall() {
	var activeCallid = "";
	var holdCallid = "";
	
	if(call1.state == 2){
		activeCallid = call1.callid;
		holdCallid = call2.callid;
	}
	
	if(call2.state == 2){
		activeCallid = call2.callid;
		holdCallid = call1.callid;
	}
	onMessage("call1: " + JSON.stringify(call1) + "  call2: " + JSON.stringify(call2))
	onMessage("_alternateCall " + phone.deviceId +" holdcall " + holdCallid +" activecall:" +  activeCallid);
    var req = {
        activeCall: activeCallid,
        holdCall: holdCallid,
         device: phone.deviceId,
        domain: phone.domain,
        type:"11"
    };
    send(req);
}

function _transferCall() {
    onMessage("_transferCall " + phone.deviceId +" holdcall " + call1.callid +" activecall:" +  call2.callid);
    var req = {
        activeCall: call2.callid,
        holdCall: call1.callid,
        device: phone.deviceId,
        domain: phone.domain,
        type:"13"
    };
    send(req);
}

function _conferenceCall() {
	var activeCallid = "";
	var holdCallid = "";
	if(call1.state == 2){
		activeCallid = call1.callid;
		holdCallid = call2.callid;
	}
	if(call2.state == 2){
		activeCallid = call2.callid;
		holdCallid = call1.callid;
	}
	onMessage("_conferenceCall " + phone.deviceId +" holdcall " + call1.callid +" activecall:" +  call2.callid);
    var req = {
        activeCall: activeCallid,
        holdCall: holdCallid,
        device: phone.deviceId,
        domain: phone.domain,
        type:"14"
    };
    send(req);
}

function _reconnectCall() {
	var activeCallid = "";
	var holdCallid = "";
	
	if(call1.state == 2){
		activeCallid = call1.callid;
		holdCallid = call2.callid;
	}
	
	if(call2.state == 2){
		activeCallid = call2.callid;
		holdCallid = call1.callid;
	}
    onMessage("_reconnectCall " + phone.deviceId +" holdcall " + call1.callid +" activecall:" +  call2.callid);
    var req = {
        activeCall: activeCallid,
        holdCall: holdCallid,
        device: phone.deviceId,
        domain: phone.domain,
        type:"12"
    };
    send(req);
}

function _sstCall(fromDevId) {
    // litenMap 为空,或者litenMap.get(fromDevId) 为false则拦截
    debugger;
    if (!litenMap || !litenMap.get(fromDevId)){
        ztoDialog("message",'请先监听再拦截!');
        window.parent.closeLoad()
        return ;
    }
    _hangupCall();//挂断电话

    setTimeout(function () {
        writeLog("_sstCall " + fromDevId +" to " + deviceId);
        var req = {
            uuid: "0",
            device: fromDevId,
            deviceTo:deviceId,
            domain: phone.domain/*,
        businessScenario:phone.deviceId,
        type:"7"*/
        };
        //send(req);
        // var url ="http://10.206.33.152:8083/agentMonitor/sstcall";
        var url =call_yunhuIp_listen+"/agentMonitor/sstcall";

        yunhuAjax(url,JSON.stringify(req),function (response) {
            writeLog("lanjie"+JSON.stringify(response))
            if (response.code=="200") {
                litenMap.delete(fromDevId);
                ztoDialog("message",'拦截成功!');
                window.parent.closeLoad()
            }else{
                console.log(response);
                ztoDialog("message",'拦截失败!请检查要拦截的话务员状态');
                window.parent.closeLoad()
            }
        })
    },1000);//拦截方法做封装延时1秒执行
    // writeLog("_sstCall " + fromDevId  +" activecall"  +" to " + deviceId);
    // var req = {
    //     uuid: "0",
    //     device: fromDevId,
    //     deviceTo:deviceId,
    //     domain: phone.domain/*,
    //     businessScenario:phone.deviceId,
    //     type:"7"*/
    // };
    // //send(req);
    // // var url ="http://10.206.33.152:8083/agentMonitor/sstcall";
    // var url =call_yunhuIp_listen+"/agentMonitor/sstcall";
    //
    // yunhuAjax(url,JSON.stringify(req),function (response) {
    //     if (response.code=="200") {
    //         litenMap.delete(fromDevId);
    //         ztoDialog("message",'拦截成功!');
    //         window.parent.closeLoad()
    //     }else{
    //         console.log(response);
    //         ztoDialog("message",'拦截失败!请检查要拦截的话务员状态');
    //         window.parent.closeLoad()
    //     }
    // })
    //setTimeout(send(req),1000);
}

/**
 * 拦截方法做封装
 * @param fromDevId
 */
function lanjie(fromDevId) {
    writeLog("_sstCall " + fromDevId +" to " + deviceId);
    var req = {
        uuid: "0",
        device: fromDevId,
        deviceTo:deviceId,
        domain: phone.domain/*,
        businessScenario:phone.deviceId,
        type:"7"*/
    };
    //send(req);
    // var url ="http://10.206.33.152:8083/agentMonitor/sstcall";
    var url =call_yunhuIp_listen+"/agentMonitor/sstcall";

    yunhuAjax(url,JSON.stringify(req),function (response) {
        writeLog("lanjie"+JSON.stringify(response))
        if (response.code=="200") {
            litenMap.delete(fromDevId);
            ztoDialog("message",'拦截成功!');
            window.parent.closeLoad()
        }else{
            console.log(response);
            ztoDialog("message",'拦截失败!请检查要拦截的话务员状态');
            window.parent.closeLoad()
        }
    })
}

function _sscCall(devId) {
    onMessage("_sscCall " + phone.deviceId  +" activecall" +  call1.callid +" to " + devId);
    var req = {
        uuid: call1.callid,
        deviceTo:devId,
        device: phone.deviceId,
        domain: phone.domain,
        type:"8"
    };
    send(req);
}
// 挂机
function _hangupCall() {
	var activeCallid = "";
    var activeCallInfo = null;
	if(call1 != null && (call1.state == 1 || call1.state == 2)){
		activeCallid = call1.callid;
        activeCallInfo = call1;
	}else if(call2 != null && (call2.state == 1 || call2.state == 2)){
	    activeCallid = call2.callid;
        activeCallInfo = call2;
    }
    //呼入转接满意度
    if(activeCallInfo != null){
        if(phone.isHoldCall){
            window.parent.closeLoad()
            writeLog("_hangupCall isHoldCall 对不起,坐席正忙,无法进行状态切换操作!");
            ztoDialog("对不起,坐席正忙,无法进行状态切换操作!");
            return;
        }
        onMessage("_hangupCall " + phone.deviceId  +" activecall:" +  activeCallid);
        if(activeCallInfo.dnis == phone.deviceId){
            window.parent.closeLoad()
            _transferSatisfaction(activeCallInfo.callid,phone.deviceId,phone.satisfactionDeviceId);
        }else{
            var req = {
                uuid: activeCallid,
                device: phone.deviceId,
                domain: phone.domain,
                type:"5"
            };
            window.parent.closeLoad()
            send(req);
        }
	}
}

//转接满意度
function _transferSatisfaction(callId,fromDevId,toDevId) {
    writeLog("_sstCall满意度 " + fromDevId  +" activecall:" +  callId +" to " + toDevId);
    var req = {
        uuid: callId,
        device: fromDevId,
        domain: phone.domain,
        deviceTo:toDevId,
        businessScenario:fromDevId,
        type:"7"
    };
    send(req);
}

function _sendDTMF(){
    var dtmf=prompt("请输入dtmf"); 
    if (dtmf!=null && dtmf!=""){ 
        if(call1 == null){
            alert("no call");
            return;
        }
        var req = {
             uuid: call1.callid,
             device: phone.deviceId,
             domain: phone.domain,
             dtmf:dtmf,
             type:"15"
        };
       send(req);
   } 
}

function shixian(){
    if (call1 != null || call2 != null) {
        if(phone.isHoldCall){
            writeLog("_shixian isHoldCall 对不起,坐席正忙,无法进行状态切换操作!");
            ztoDialog("对不起,坐席正忙,无法进行状态切换操作!");
            return false;
        }else if(call1.state ==2||(call2 != null&&call2.state == 2)){//接通,取回通话
            $('#callStatus').html("已接通");
            return false;
        }
        return false;
    }
    writeLog(phone.agtId+" 操作了空闲");
    _setAgentStateS(phone.domain,phone.deviceId,phone.agtId, "0", "Ready", "101", workMode);
}
function shimang(){
    if (call1 != null || call2 != null) {
        if(phone.isHoldCall){
            writeLog("_shimang isHoldCall 对不起,坐席正忙,无法进行状态切换操作!");
            ztoDialog("对不起,坐席正忙,无法进行状态切换操作!");
            return false;
        }else if(call1.state ==2||(call2 != null&&call2.state == 2)){//通话
            $('#callStatus').html("暂停");
            return false;
        }
        return;
    }
     writeLog(phone.agtId+" 操作了暂停");
    _setAgentStateS(phone.domain,phone.deviceId,phone.agtId, "1", "NotReady", "101", workMode);
}

/**
* 查询壹米滴答话务中心下的所有技能组
*/
function getGroups() {
    var skIllGroupList=new Array();
    var metricsReq = {
        id:new Date().getTime(),
        serviceMap:{
            "0":{
                attributes:[
                    "channel.voice",
                    "domain."+call_domain
                ]
            }
        }
    };
   /* var action = {
        action: call_yunhuIp+ '/acd/services/metrics' ,
        data: metricsReq
    };*/
    var url = call_yunhuIp+ '/acd/services/metrics' ;
    yunhuAjax(url,JSON.stringify(metricsReq),function(response){
        if(!isNull(response)){
            if(!isNull(response.serviceMetricsResponseMap)){
                var responseMap = response.serviceMetricsResponseMap;
                for(var key  in responseMap){
                    console.log(key + '---'+responseMap[key]);
                    var skillGroup = {
                        skillId:responseMap[key].attributes[1],
                        skillName:responseMap[key].attributes[2]
                    };
                    skIllGroupList[key]=skillGroup;
                };
                // console.log();
                litenMap = new Map();//查询技能组时会把litenmap清空
                window.parent.openBzDialog(skIllGroupList)
            }
            console.log(response);
        }else{
            console.log(response);
            writeLog('获取技能组失败！');
        }
    });
    return skIllGroupList
}


/**
 *根据技能组id查询用户
 */
function getGroupByUser(index,skillId) {

    var userList =new Array();
    var metricsReq = {
        id:new Date().getTime(),
        serviceMap:{
            "0":{
                attributes:[
                    "channel.voice",
                    skillId,
                    "domain."+call_domain
                ]
            }
        }
    };
    var url = call_yunhuIp+ '/acd/services/metrics' ;
    debugger;
    yunhuAjax(url,JSON.stringify(metricsReq),function (response) {
        if (!isNull(response)) {
            //_setAgentState(device, domain, username, pwd, "0", "Login", "101", workMode);
            // _setAgentState(device,domain,username,pwd,"0","Login","101","AutoIn");
            console.log(response);
            if(!isNull(response.serviceMetricsResponseMap)){
                console.log(true);
                var responseMap = response.serviceMetricsResponseMap;
                for(var key  in responseMap){
                    console.log(key + '---'+responseMap[key]);
                    var user = {
                        userCode:responseMap[key].metrics.AgentId,
                        userName:responseMap[key].metrics.AgentName,
                        userStatus:getUserStatus(responseMap[key].metrics.AgentState),
                        userDeiceNum:responseMap[key].metrics.StationId,
                        status:responseMap[key].metrics.AgentState
                    };
                    userList[key]=user;
                }
                console.log(userList);
                window.parent.datagridFun(userList,index)
            }
        }else{
            console.log(response);
            writeLog('获取坐席失败！');
        }
    });
}

/**
 * 对坐席状态进行转换
 * @param agentState
 * @returns {string}
 */
function getUserStatus(agentState) {
    if (agentState == 'ResourceReady') {
        return "就绪";
    } else if (agentState == 'ResourceNotReady') {
        return "未就绪";
    } else if (agentState == 'ResourceWrapUp') {
        return "话后处理";
    } else if (agentState == 'ResourceEnable') {
        return "未就绪";
    } else if (agentState == 'ResourceDisable') {
        return "未登录";
    } else if  (agentState == 'ResourceAux') {
        return"离席";
    } else if (agentState == 'ResourceAtWork') {
        return "通话中";
    } else if (agentState == 'ResourceRing') {
        return "振铃中";
    } else if (agentState == 'ResourceRingback') {
        return "回铃中";
    }

}

function cleaMap() {
    litenMap =  new Map();//取消监听时吧监听表示清空
}

/**
 * 话务监听接口
 * @param dev_id 被监听的分机号   getGroupByUser  中的  userDeiceNum
 * @param device_to 去监听的分机号 当前登录人员的分机号
 * device_to 监听  dev_id
 */
var litenMap = new Map();
function agentListen(dev_id, device_to){
    // window.parent.jtsucc();
    if (call1 != null || call2 != null) {
        //如果正在通话中不可以进行监听
        ztoDialog('本机正在通话中!不可以监听和拦截!');
        window.parent.closeLoad()
        return ;
    }
    writeLog("agentListen " + dev_id  +" to " + device_to);
    var req = {
        uuid: '0',
        device: dev_id,
        domain: phone.domain,
        uui: "",
        deviceTo:device_to
    };

    debugger;
    //var url = "http://"+phone.webUrl +'/gw/rest/spycall';
    // var url ="http://10.206.33.152:8083/agentMonitor/spycall";
    var url =call_yunhuIp_listen +"/agentMonitor/spycall";
    yunhuAjax(url,JSON.stringify(req),function (response) {
        console.log("agentListen"+JSON.stringify(response))
        if (response.code=="200") {
            ztoDialog("message",'监听成功！');
            litenMap.set(dev_id,true);
            window.parent.jtsucc();
        }else if(response.code=="202"){
            if(response.errMsg.indexOf(" is listening ")>0){
                ztoDialog('分机已被监听，'+response.errMsg);
                litenMap.set(dev_id,false);
            }else{
                window.parent.closeLoad();
                litenMap.set(dev_id,false);
                ztoDialog("message",'监听失败！'+response.errMsg);
            }
        }
    })
    /*DataSvc.send(action, function (response) {
        if (response.success) {
            ztoDialog('监听成功！');
            console.log(response);
            litenMap.set(dev_id,true);
            window.parent.jtsucc();
        }else{
            //alert("_sstCall Fail !");
            litenMap.set(dev_id,false);
            ztoDialog('监听失败！请确保要监听的员工正在通话中!');
        }
    });*/
}

/**
 * 设置最后通话字段
 * @param event
 */
function setLastCall(event){
    phone.lastCall.callId = event.callId="undefined"?event.callId:null;
    //过滤排队事件
    if(phone.lastCall.evtName != "QueueCallChangeEvt"){
        phone.lastCall.evtName = event.evtName="undefined"?event.evtName:null;
    }
    /*callId:0,
     subId:0,
     areaCode:"",
     ani:"",
     groupId:"",
     ivrList:"",
     offHookTime:""*/
}


/**
 * jQuery ajax请求
 * @param url 请求路径
 * @param data 请求参数
 * @param callback 回调方法
 * @param type 请求方式,POST/GET,默认Post
 */
function yunhuAjax(url, data, callback, type) {
    if (!type) {
        type = 'POST';
    }
    $.ajax({
        type: type,
        url: url,
        data: data,
        timeout: 3000,
        contentType: "application/json;charset=utf-8",
        success : function(data){
            var result = data;
            if (typeof data == 'string') {
                result = eval('('+ data +')');
            }
            if (result.message) {
                result.success ? showTips(result.message,'success') : showError(result);
            }
            if(callback){
                callback.apply(this, [result]);
            }
        },
        error: function (xhr, status, error) {
            console.log(xhr);
            console.log(status);
            console.log(error);
        }
    });
}

isNull = function(str){
    if(typeof str == "undefined"){
        return true;
    }else if(str == null){
        return true;
    }else if(typeof str == "string" && (str === "" || str === "undefined" || str === "null")){
        return true;
    }else if(typeof str == "object" && $.isArray(str) && str.length == 0){
        return true;
    }else if(typeof str == "object" && $.isEmptyObject(str)){
        return true;
    }else{
        return false;
    }
}
